#coding=utf-8

from lib.tornado_routes import route
from web.handler import BaseHandler
from tornado import gen
from tornado.web import asynchronous
from web.models.user.auth.register import Register
# from decorator.auth import admin_login_required, admin_auth
from lib.libsms import sent
import time
import json


@route(r'/user/register/?', name='user.register')
class IndexHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self):
        self.render("user/auth/zhuce.html",)

    @asynchronous
    @gen.coroutine
    def post(self):
        login_name = self.get_argument('name',default='')
        pwd = self.get_argument('password', default='')
        pwd2 = self.get_argument('password2', default='')
        school_id = self.get_argument('schoolId', default=1)
        tel = self.get_argument('tel', default='')
        code = self.get_argument('code', default='')

        self.write(str(self.get_scookie()))
        self.write(tel+','+code)

        if login_name == '' or pwd == '' or pwd2 == '' or pwd != pwd2:
            print 'bad register'
        elif tel == self.get_scookie().get('info').get('tel') and code == self.get_scookie().get('info').get('code'):
            result = yield Register().register(login_name, pwd, school_id)
        else:
            self.write('验证码错误')
            return

        self.redirect('/user/info/insert')

@route(r'/user/register/getcode?', name='user.getcode')
class CodeHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self):
        tel = self.get_argument('tel',default='')

        if tel != '':
            code = str(int(time.time()*100000%100000))
            ret = sent(tel, code)
            xret = json.loads(ret)
            if xret.get('error_code') == 0:
                self.set_scookie('info', {'tel':tel, 'code':code})
                self.write('0')
            else:
                self.write(ret)


@route(r'/user/info/insert?', name='user.info.insert')
class InfoHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self):
        self.render("user/auth/zhuce_step2.html",)

    @asynchronous
    @gen.coroutine
    def post(self):

        self.redirect('/user/student')